package com.learn.queue.safety.blocking;

import com.learn.constant.MathConstant;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 测试LinkedBlockingQueue
 */
public class LinkedBlockingQueueTest {

    public static void main(String[] args) throws InterruptedException {

        // 声明一个容量为10的缓存队列
        BlockingQueue<String> queue = new LinkedBlockingQueue<>(MathConstant.INT_TEN);

        ExecutorService service = Executors.newCachedThreadPool();

        // 消费者的线程
        for (int i = MathConstant.INT_ZERO; i < MathConstant.INT_ONE; i++) {
            Consumer consumer = new Consumer(queue,i);
            service.execute(consumer);
        }
        // 生产者的线程
        List<Producer> producerList = new ArrayList<>();
        for (int i = MathConstant.INT_ZERO; i < MathConstant.INT_FIVE; i++) {
            Producer producer = new Producer(queue,i);
            producerList.add(producer);
            service.execute(producer);
        }

        // 生产10秒停止生产
        Thread.sleep(10 * 1000);
        producerList.forEach(Producer::stop);

        Thread.sleep(2000);

        // 退出Executor
        service.shutdown();

    }
}
